//
//  LGStatusBarManager.m
//  HideStatusBarDemo
//
//  Created by lg on 31/10/2019.
//  Copyright © 2019 lg. All rights reserved.
//

#import "LGStatusBarManager.h"
#import <UIKit/UIKit.h>
#import <objc/runtime.h>

@implementation LGStatusBarManager

// 创建单例的关键代码
static id instance = nil;

+ (instancetype)sharedInstance {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[self alloc] init];
    });
    return instance;
}

// 这个方法是关键
+ (instancetype)allocWithZone:(struct _NSZone *)zone {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [super allocWithZone:zone];
    });
    return instance;
}

- (void)setStatusBarHidden:(BOOL)hide {
    _statusBarHide = hide;
    @try {
//        UIApplication *app = [UIApplication sharedApplication];
//        UIView *statusBar = [app valueForKeyPath:@"statusBar"];
        UIStatusBarManager *barManager = [UIApplication sharedApplication].keyWindow.windowScene.statusBarManager;
        
        unsigned int count;
        //获取属性列表
        objc_property_t *propertyList = class_copyPropertyList([UIStatusBarManager class], &count);
        for (unsigned int i=0; i<count; i++) {
            const char *propertyName = property_getName(propertyList[i]);
            NSLog(@"property----="">%@", [NSString stringWithUTF8String:propertyName]);
        }
        
        //获取方法列表
        Method *methodList = class_copyMethodList([self class], &count);
        for (unsigned int i; i<count; i++) {
            Method method = methodList[i];
            NSLog(@"method----="">%@", NSStringFromSelector(method_getName(method)));
        }
        
        //获取成员变量列表
        Ivar *ivarList = class_copyIvarList([UIStatusBarManager class], &count);
        for (unsigned int i; i<count; i++) {
            Ivar myIvar = ivarList[i];
            const char *ivarName = ivar_getName(myIvar);
            NSLog(@"ivar----="">%@", [NSString stringWithUTF8String:ivarName]);
        }
        
        [barManager performSelector:@selector(setStatusBarHidden:) withObject:@(hide)];
//        [barManager setValue:@(hide) forKey:@"statusBarHidden"];
//        [barManager setValue:hide?@(0):@(1) forKey:@"statusBarAlpha"];
//        UIView *_localStatusBar = [barManager performSelector:@selector(createLocalStatusBar)];
//        UIView *statusBar = [_localStatusBar performSelector:@selector(statusBar)];
//
//        statusBar.backgroundColor = [UIColor redColor];
//        [statusBar setHidden:hide];
//        UIView *view = [barManager valueForKey:@"localStatusBars"];
//        [view setHidden:hide];
//        [statusBar setHidden:hide];
    } @catch (NSException *exception) {
        NSLog(@"%@", exception.reason);
    } @finally {
        
    }
    
}

@end

@implementation UIViewController (LGStatusBar)

- (BOOL)prefersStatusBarHidden
{
    return [LGStatusBarManager sharedInstance].statusBarHide;
}

@end
